<template>
  <div v-if="isLogin">
    <el-progress :percentage="currentPercent" :stroke-width="15" status="success" striped striped-flow :duration="10"
      :show-text="false" class="exam-progress" />
    <h1 align="center">考试</h1>
    <div class="timer">
      剩余时间：{{ remindMins }} 分钟 {{ remindSeconds }} 秒
    </div>

    <el-card class="question">
      <h3>
        <!-- 问题1: 测试问题11111 -->
        {{ currentQuestionIndex + 1 }}. {{ currentQuestion.title }}
      </h3>
      <div class="question-body">
        <div class="answer-list">
          <el-radio-group v-model="form[currentQuestion.fieldName]" v-if="currentQuestion.type === QuestionType.SINGLE">
            <el-radio :value="item.value" v-for="(item, index) of currentQuestion.answerList" size="large"
              style="width: 100%">{{ `${item.value}. ${item.label}` }}</el-radio>
          </el-radio-group>
          <div v-if="currentQuestion.type === QuestionType.MULTIPLE">
            <el-checkbox-group v-model="form[currentQuestion.fieldName]" size="small">
              <el-checkbox v-for="(v, index) of currentQuestion.answerList" :label="`${v.value}. ${v.label}`"
                :value="v.value" size="large" class="checkbox-answer" />
            </el-checkbox-group>
          </div>
          <div v-if="currentQuestion.type === QuestionType.TRUEFALSE">
            <el-radio-group v-model="form[currentQuestion.fieldName]">
              <el-radio :value="v.value" size="large" style="width: 100%"
                v-for="(v, index) of currentQuestion.answerList">{{ `${v.value}. ${v.label}` }}</el-radio>
            </el-radio-group>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button type="primary" v-if="currentQuestionIndex === 0" style="width: 100%"
          @click="nextQuestion">下一题</el-button>
        <el-button-group style="width: 100%" v-else-if="currentQuestionIndex !== questionList.length - 1">
          <el-button type="warning" style="width: 50%" @click="beforeQuestion">上一题</el-button>
          <el-button type="primary" style="width: 50%" @click="nextQuestion">下一题</el-button>
        </el-button-group>
        <el-button-group style="width: 100%" v-else>
          <el-button type="warning" style="width: 50%" @click="beforeQuestion">上一题</el-button>
          <el-button type="success" style="width: 50%" @click="() => submit('default')">提交</el-button>
        </el-button-group>
      </template>
    </el-card>
  </div>
  <div v-else style="
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
    ">
    <h1 style="text-align: center">登录</h1>
    <el-form :model="loginForm" ref="formRef" :rules="rules" label-position="top" style="width: 80%">
      <el-row>
        <el-form-item prop="staffName" label="姓名" label-width="80px" style="width: 100%">
          <el-input v-model="loginForm['staffName']" />
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item prop="staffIdentity" label="身份证号" label-width="80px" style="width: 100%">
          <el-input v-model="loginForm['staffIdentity']" />
        </el-form-item>
      </el-row>
      <!-- <el-row>
        <el-form-item prop="companyName" label="电话号码" label-width="80px" style="width: 100%">
          <el-input v-model="loginForm['phone']" />
        </el-form-item>
      </el-row> -->
      <!-- <el-row>
        <el-form-item prop="phone" label="公司名称" label-width="80px" style="width: 100%">
          <el-input v-model="loginForm['phone']" />
        </el-form-item>
      </el-row> -->
      <!-- <el-row>
        <el-form-item prop="areaId" label="省市区" label-width="80px" style="width: 100%">
          <CitySelect v-model="loginForm['areaId']" key="areaId" @update:model-value="(v) => getAreaLists(v)" />
        </el-form-item>

      </el-row> -->
      <!-- <el-row>
        <el-form-item prop="provinceId" label="省" label-width="80px" style="width: 100%"> -->
          <!-- <CitySelect v-model="form['provinceId']" key="areaId" @update:model-value="(v) => getAreaLists(v)" /> -->
            <!-- <SingleLayerSelect v-model="loginForm['provinceId']" :options="provinceList" @update:modelValue="(v)=>getCityList(v)"/>
        </el-form-item>

      </el-row> -->

      <!-- <el-row>
        <el-form-item prop="cityId" label="市" label-width="80px" style="width: 100%"> -->
          <!-- <CitySelect v-model="form['provinceId']" key="areaId" @update:model-value="(v) => getAreaLists(v)" /> -->
            <!-- <SingleLayerSelect v-model="loginForm['cityId']" :options="cityList" @update:modelValue="(v)=>getAreaList(v)"/>
        </el-form-item>
      </el-row> -->

      <!-- <el-row>
        <el-form-item prop="areaId" label="区" label-width="80px" style="width: 100%"> -->
          <!-- <CitySelect v-model="form['provinceId']" key="areaId" @update:model-value="(v) => getAreaLists(v)" /> -->
            <!-- <SingleLayerSelect v-model="loginForm['areaId']" :options="areaList" @update:modelValue="(v)=>getTownList(v)"/> </el-form-item>
      </el-row> -->

      <!-- <el-row>
        <el-form-item prop="townId" label="乡镇" label-width="80px" style="width: 100%">
          <SingleLayerSelect :options="townList" v-model="loginForm['townId']" />
        </el-form-item>
      </el-row> -->

      <el-row justify="center">
        <el-button type="primary" style="width: 100%" @click="login">确认</el-button>
      </el-row>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { FormRules } from "element-plus";
import AccountApi from "~/src/api/AccountApi";
import { useUserStore } from "~/src/store/modules/user";
import dayjs from 'dayjs'

const loginForm = reactive<Record<string, any>>({});
const router = useRouter();
const remindMins = ref();
const remindSeconds = ref();
const endTime = ref<Date>(new Date());
// const form = ref<Record<string, any>>({});
let form = reactive<Record<string, any>>({});
// const form = ref<Record<string, any>>({});
const formRef = useTemplateRef("formRef");
const rules = ref<FormRules>({
  staffName: {
    required: true,
    message: "请输入姓名",
    trigger: "blur",
  },
  staffIdentity: {
    required: true,
    message: "请输入身份证号码",
    trigger: "blur",
  },
  // phone: {
  //   required: true,
  //   message: "请输入手机号",
  //   trigger: "blur",
  // },
  // provinceId: {
  //   required: true,
  //   message: "请选择省",
  //   trigger: "blur",
  // },
  // cityId: {
  //   required: true,
  //   message: "请选择市",
  //   trigger: "blur",
  // },
  // areaId: {
  //   required: true,
  //   message: "请输入区域",
  //   trigger: "blur",
  // },
  // townId: {
  //   required: true,
  //   message: "请输入乡镇",
  //   trigger: "blur",
  // },
});

// 倒计时计时器
let intervalId: any;
const drillExamInfoId = ref("");
const drillInfoId = ref("");
const companyId = ref("");
const examInfo = ref();
const isLogin = ref(false);
const isSubmit = ref(false);
const showSubmit = ref(false);
const currentPercent = computed(
  () => ((currentQuestionIndex.value + 1) / questionList.value.length) * 100
);
const currentQuestionIndex = ref(0);

const currentQuestion = computed(() => {
  return questionList.value[currentQuestionIndex.value];
});
enum QuestionType {
  SINGLE = "单选题",
  MULTIPLE = "多选题",
  TRUEFALSE = "判断题",
}

const store = useUserStore();
const questionList = ref();
let counter = 0;
function getRemindTime() {
  const currentDate = new Date();
  // console.log("endTime.value", endTime.value);

  const endTimeObj = dayjs(endTime.value)
  const seconds = endTimeObj.diff(currentDate, "s")
  // const mins =
  //   (endTime.value.getHours() - currentDate.getHours()) * 60 +
  //   endTime.value.getMinutes() -
  //   currentDate.getMinutes();
  // const seconds = endTime.value.getSeconds() - currentDate.getSeconds();
  // remindMins.value = Math.floor((mins * 60 + seconds) / 60);
  // remindSeconds.value = (mins * 60 + seconds) % 60;
  remindMins.value = Math.floor(seconds / 60)
  remindSeconds.value = seconds % 60

  endTimeObj.subtract(1, "m")
  const finalSubmitTime = new Date(endTime.value)
  console.log("end time",endTime.value.toString())

  // if (finalSubmitTime.getMinutes() === 0) {
  //   finalSubmitTime.setHours(finalSubmitTime.getHours() - 1)
  //   finalSubmitTime.setMinutes(59)
  // } else {
  //   finalSubmitTime.setMinutes(finalSubmitTime.getMinutes() - 1)
  // }
  console.log("final time",finalSubmitTime.toString())

  // 超时自动提交
  if (isLogin.value && finalSubmitTime.getTime() < new Date().getTime()) {
    if (!isSubmit.value && counter < 5 && !showSubmit.value) {
      submit("expire");
      showSubmit.value = true;
    }
  }
}
const provinceList = ref([])
const cityList = ref([])
const areaList = ref([])
const townList = ref([])

function getProvinceList() {
  AccountApi.getProvinceList({}).then((res) => {
    provinceList.value = res.data
      .map((item: any) => ({ label: item.province, value: item.provinceId }))
  })
}

function getCityList(v: any) {
  AccountApi.getCityList({ provinceId: v }).then((res) => {
    cityList.value = res.data
      .map((item: any) => ({ label: item.city, value: item.cityId }))
  })
}

function getAreaList(v: any) {
  AccountApi.getNormalAreaList({ cityId: v }).then((res) => {
    areaList.value = res.data
      .map((item: any) => ({ label: item.area, value: item.areaId }))
  })
}

function getTownList(v: any) {

  AccountApi.getTownList({ areaId: v }).then((res) => {
    console.log("乡镇", res.data.
      records
    );
    townList.value = res.data.records
      .map((item: any) => ({ label: item.town, value: item.townId }))
  })
}
function startCountDown() {
  if (intervalId) {
    clearInterval(intervalId)
  }
  getRemindTime();
  intervalId = setInterval(getRemindTime, 1000);
}
onMounted(() => {
  const url = new URL(window.location.href);
  console.log("url", url);
  const examId = url.searchParams.get("examId") ?? "";
  console.log("examId", examId);
  getProvinceList()
});

function beforeQuestion() {
  if (currentQuestionIndex.value === 0) {
    $baseMessage("已抵达最开始题目", "success");
  } else {
    currentQuestionIndex.value -= 1;
  }
}
function nextQuestion() {
  if (currentQuestionIndex.value === questionList.value.length - 1) {
    $baseMessage("已全部完成", "success");
  } else {
    currentQuestionIndex.value += 1;
  }
}

function resetForm() {
  // 清空所有答题记录
  // 清空所有答题记录
  Object.keys(form).forEach(key => {
    delete form[key];
  });
  // form = { }
  // 重置到第一题
  startExam()
  currentQuestionIndex.value = 0;
  console.log("考试记录已重置，回到第一题");
}
// 调取考试信息
// function doSave() {
//   AccountApi.getExamRecord().then((res) => {
//     if (res.data.records[0].pass == 1) {
//       // 调用重置方法
//       resetForm();
//       $baseMessage("考试未通过,请重新考试", "error");
//     } else {
//       $baseMessage("考试通过", "success");
//     }
//   })
// }
const pass = ref()
function doSave() {
  AccountApi.getExamRecord().then((res) => {
    console.log("考试记录", res.data);
    console.log("考试状态", res.data.records[0].pass);
    pass.value = res.data.records[0].pass;
    console.log("pass111", typeof (pass.value));
    // 考试不通过时不跳转页面
    if (pass.value == 1) {
      // AccountApi.startExam({ drillExamInfoId: drillExamInfoId.value })
      $baseConfirm("考试未通过,点击确认重新考试","重新考试",function confirm(){
        resetForm()
      },function cancel(){
        router.push("/examResult");
      })
      // $baseMessage("考试未通过,请重新考试", "error");
    } else {
      // 考试通过时才跳转
      // if (v && v.success) {
      //   clearInterval(intervalId)
      //   console.log("submit exam result", v);
      router.push("/examResult");
      // }
    }
  })
}

function doSubmit() {
  const dataList: any[] = [];
  // 已填写项
  for (const key of Object.keys(form)) {
    if (key.includes("subject")) {
      const value = form[key].join
        ? form[key].sort((a, b) => a.charCodeAt(0) - b.charCodeAt(0)).join("")
        : form[key];
      dataList.push({
        paperId: +key.split("-")[1],
        userOptions: value,
      });
    }
  }

  // 未填写项
  for (const question of questionList.value) {
    if (!form[question.fieldName]) {
      dataList.push({
        paperId: question.fieldName.split("-")[1],
        userOptions: ""
      })
    }
  }

  AccountApi.submitExam({
    drillExamInfoId: drillExamInfoId.value,
    dataList,
  }).then((v) => {
    console.log(11111, v);
    doSave();
    // console.log('pass222', pass.value);
    if (v && v.success) {
      clearInterval(intervalId)
      console.log("submit exam result", v);
      // router.push("/examResult");
    }
    counter++;
    isSubmit.value = true;
  });
}

function submit(type = "default") {
  console.log("submit type", type)
  questionList.value
  
  console.log("questionList",questionList.value, "form",form)
  let unFilledQuestionIndex:number | undefined
  questionList.value.some((question: {fieldName: string},index: number)=>{
    // 当前已填写列表中没有对应题目的时候弹窗提示
    console.log("question.fieldName",question.fieldName,"form[question.fieldName]",form[question.fieldName])
    if (!form[question.fieldName]) {
      unFilledQuestionIndex = index
      return true 
    //  return await new Promise((resolve,rejct)=>{
    //     $baseConfirm("当前有未填写的题目，点击确认跳转到第一个未填写的题目,点击取消忽略提示直接提交","题目未填写",function confirm(){
    //       // 确认则跳转到第一个未填写题目
    //       currentQuestionIndex.value = index
    //       resolve(true)
    //     },function cancel(){
    //       doSubmit()
    //     })
    //   })
    }
    return false
  })
  
  // 距离考试一分钟时提示强制提交
  if (type === "expire") {
      $baseAlert("距离考试结束还有一分钟，请确认提交试卷","提交试卷",function confirm(){
        doSubmit()
      })
      // $baseMessage("已超过考试时间，倒计时5秒钟后自动提交试卷");
      // setTimeout(() => {
      //   doSubmit();
      // }, 5000);
  } else {
    if (unFilledQuestionIndex) {
      // 还有一分钟结束考试时，还有未填写的题目与手动点击提交时的提示信息不同
      // const message = type === 'expire' ? "距离考试结束还有一分钟，当前有未填写的题目，点击确认跳转到第一个未填写的题目,点击取消忽略提示直接提交" : "当前有未填写的题目，点击确认跳转到第一个未填写的题目,点击取消忽略提示直接提交"
      $baseConfirm("当前有未填写的题目，是否确认提交","试卷提交",function confirm(){
        // 确认则跳转到第一个未填写题目
        // currentQuestionIndex.value = unFilledQuestionIndex! 
        doSubmit()
      },function cancel(){
        // 取消直接提交，无视未填写题目
      })
    } else {
      if (type === "default") {
        $baseConfirm("确认提交试卷吗？", "提交确认", doSubmit, () => { });
      }  
    }
  }
}
onMounted(() => {
  const url = new URL(window.location.href);
  console.log("url", url);
  companyId.value = url.searchParams.get("companyId") ?? "";
  drillExamInfoId.value = url.searchParams.get("drillExamInfoId") ?? "";
  drillInfoId.value = url.searchParams.get("drillInfoId") ?? "";
});


function startExam(){
  AccountApi.startExam({ drillExamInfoId: drillExamInfoId.value }).then(
    (startExamRes) => {
      if (!startExamRes || (!startExamRes.success && startExamRes.message !== "您已开始考试")) {
        return;
      }
      AccountApi.examDetail({
        drillExamInfoId: drillExamInfoId.value,
      }).then((examDetailRes) => {
        if (!examDetailRes || !examDetailRes.success) {
          return;
        }
        startCountDown()
        examInfo.value = examDetailRes.data;
        endTime.value = new Date(examDetailRes.data.endTime);
        questionList.value = examDetailRes.data.dataList.map((v) => {
          const answerList = [];
          for (const key of Object.keys(v).filter((x) =>
            x.includes("option")
          )) {
            // console.log("option key", key);
            if (v[key] !== "") {
              answerList.push({
                label: v[key],
                value: key.split("option")[1],
              });
            }
          }
          return {
            type: v.subjectType,
            title: v.subjectContent,
            fieldName: `subject-${v.id}`,
            answerList,
          };
        });
        isLogin.value = true;
      });
    }
  );
}
function action(obj?: {id?: any, name?: string, type?: any}) {
  // const form:Record<any,any> = {}
  // obj.id && (form.companyId = obj.id)
  // obj.type && (form.companyType = obj.type)
  // form.companyName = obj.name
  
  AccountApi.h5UserLogin({
    // ...form,
    ...loginForm,
    drillId: drillInfoId.value
  }).then((res) => {
    if (!res || !res.success) {
      return;
    }
    console.log("data token", res.data.token);
    store.setToken(res.data.token);
    startExam()
  });
}
// const companyList = ref<{label: any, value: any, type: any}[]>([])
function login() {
  formRef.value?.validate((validate) => {
    if (validate) {
      console.log("validate");
      action({})
      // const companyListItem = {
      //   staffName: loginForm.staffName,
      //   staffIdentity: loginForm.staffIdentity,
      //   phone: loginForm.phone
      // }
      // AccountApi.getCompanyList(companyListItem).then(res => {
      //   console.log("res11111", res.data);

      //   if (res) {
      //     companyList.value = res.data.map(x => ({ label: x.companyName, value: x.companyId, type: x.companyInfo.type }))
      //     // 管理端
      //     if (companyId.value && companyId.value === "0") {

      //       if (companyList.value.length > 0) {
      //         if (companyList.value.length === 1) {
      //           const { value: id, label: name, type }  = companyList.value[0]
      //           action({id, name})
      //         } else {
      //           VDialog.open({
      //             title: "公司选择",
      //             content: {
      //               top: "35vh",
      //               //内容初始形式
      //               type: "component", //text:"",预留文本
      //               name: "/signin/companySelect",
      //               query: { options: companyList }
      //             },
      //             callBack: ({id, name}:{id: any,name: any, type: any}) => {
      //               action({id, name})
      //             },
      //             onClose: () => {
      //               console.log("对话框已关闭");
      //             },
      //           });
      //         }

      //       } else {
      //         // $baseMessage("用户不存在", "error")
      //         VDialog.open({
      //           title: "公司输入",
      //           content: {
      //             top: "35vh",
      //             //内容初始形式
      //             type: "component", //text:"",预留文本
      //             name: "/signin/company",
      //           },
      //           callBack: ({companyName: name, companyType: type} : {companyName: any, companyType: any}) => {
      //             action({name, type})
      //           },
      //           onClose: () => {
      //             console.log("对话框已关闭");
      //           },
      //         });
      //       }

      //     } else {
      //       // 商户端
      //       const currentCompany = companyList.value.find(x=>x.value === companyId.value)
      //       if (currentCompany) {
      //         action({id: companyId.value, name: currentCompany.label})
      //       } else {
      //         $baseMessage("用户不存在", "error")
      //       }
      //     }
      //   }
      // })
      // if (companyId.value && companyId.value === "0") {
      //   VDialog.open({
      //     title: "公司选择",
      //     content: {
      //       top: "35vh",
      //       //内容初始形式
      //       type: "component", //text:"",预留文本
      //       name: "/exam/companySelect",
      //       query: { staffName: loginForm.staffName, staffIdentity: loginForm.staffIdentity, phone: loginForm.phone }
      //     },
      //     callBack: (data: any) => {
      //       companyId.value = data
      //       action()
      //     },
      //     onClose: () => {
      //       console.log("对话框已关闭");
      //     },
      //   });
      // } else {
      //   action()
      // }
    }
  });
}
</script>

<style scoped>
.exam-progress {
  margin: 5px 5px;
}

.timer {
  text-align: center;
}

.question {
  display: flex;
  flex-direction: column;
  margin: 20px 5px;
}

.question-body {
  height: 85%;
  overflow: scroll;
}

.answer-list {
  overflow: scroll;
}

.checkbox-answer {
  width: 80%;
  margin-bottom: 10px;
}

:deep(.el-checkbox__label) {
  width: 100%;
  white-space: pre-wrap;
  line-height: 20px;
}

:deep(.el-card__body) {
  height: 400px;
}
</style>
